package com.mazaiting.rabbitmq.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mazaiting.rabbitmq.domain.entity.MqMessage;
import com.mazaiting.rabbitmq.domain.info.MessageInfo;
import com.mazaiting.rabbitmq.mapper.IMqMessageMapper;
import com.mazaiting.rabbitmq.service.IMqMessageService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * MQ 消息发送记录 服务实现类
 * </p>
 *
 * @author mazaiting
 * @since 2022-10-01
 */
@Service
public class MqMessageServiceImpl extends ServiceImpl<IMqMessageMapper, MqMessage> implements IMqMessageService {

    @Override
    public <T> String save(MessageInfo<T> messageInfo) {
        // snowflake 算法
        String messageId = IdWorker.getTimeId();
        // 保存消息
        MqMessage mqMessage = new MqMessage();
        mqMessage.setId(messageId);
        mqMessage.setExchange(messageInfo.getExchange());
        mqMessage.setRoutingKey(messageInfo.getRoutingKey());
        mqMessage.setBody(JSON.toJSONString(messageInfo.getData()));
        mqMessage.setExclusion(messageInfo.getExclusion());
        mqMessage.setMaxRetryCount(messageInfo.getMaxRetryCount());
        // 过期时间
        Integer expiration = messageInfo.getExpiration();
        if (Objects.nonNull(expiration) && expiration >= 0) {
            mqMessage.setExpiration(expiration);
        }
        baseMapper.insert(mqMessage);
        return messageId;
    }
}
